package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"sync"
	"time"
	"video_-chat/api/request"
	"video_-chat/global"
	"video_-chat/internal/moble"
	"video_-chat/pkg"
)

var ConnMap map[int32]request.Node = make(map[int32]request.Node)

func ChatConn(context *gin.Context) {
	var user moble.Users
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)
	upgrader := websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}
	conn, _ := upgrader.Upgrade(context.Writer, context.Request, nil)
	var Node request.Node
	Node.Conn = conn
	Node.Data = make(chan []byte)
	Node.Esc = make(chan bool)
	ConnMap[user.UserId] = Node
	var wg sync.WaitGroup

	wg.Add(2)
	go ReadSocket(Node, user, &wg)
	go WriteSocket(Node, &wg)
	wg.Wait()
	close(Node.Data)
	close(Node.Esc)
	Node.Conn.Close()
}

func WriteSocket(node request.Node, s *sync.WaitGroup) {
	defer s.Done()
	for msg := range node.Data {
		select {
		case <-node.Esc:
			{
				return
			}
		default:
			{

			}
		}
		node.Conn.WriteMessage(websocket.TextMessage, msg)
	}
}

func ReadSocket(node request.Node, user moble.Users, s *sync.WaitGroup) {
	defer s.Done()
	for {
		select {
		case <-node.Esc:
			{
				return
			}
		default:
			{

			}
		}
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			node.Esc <- true
			return
		}
		var seed request.Seed
		json.Unmarshal(message, &seed)
		status := pkg.Baidu(seed.Data)
		var Message moble.PrivateMessage
		Message = moble.PrivateMessage{
			SenderId:     user.UserId,
			ReceiverId:   int32(seed.SeedId),
			Content:      seed.Data,
			SeedTime:     time.Now(),
			IsRead:       0,
			HasSensitive: status,
		}
		global.DB.Create(&Message)
		if status != "合规" {
			node.Data <- []byte("消息不合规")
			continue
		}
		var FormMsg = request.GetData{
			ChatId:   Message.MsgId,
			Data:     seed.Data,
			FormName: user.Nickname,
			FormId:   int(user.UserId),
			FormTime: time.Now(),
		}
		set, _ := json.Marshal(FormMsg)
		ConnMap[int32(seed.SeedId)].Data <- set
	}
}

func ChatList(context *gin.Context) {
	var user moble.Users
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)
	rab := pkg.NewRabbitMQSimple(fmt.Sprintf("user:%d", user.UserId))
	msgs := rab.ConsumeSimple()
	for msg := range msgs {
		ConnMap[user.UserId].Data <- msg.Body
		var message moble.Message
		json.Unmarshal(msg.Body, &message)
		message.IsRead = 1
		global.DB.Updates(&message)
	}
}

func ReadNotCount(context *gin.Context) {
	var user moble.Users
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)
	var Follow int
	var Comment int
	global.DB.Where("receiver_id = ? and is_read = 0 and type = 0", user.UserId).Model(&moble.Message{}).Select("count(*)").Find(&Follow)
	global.DB.Where("receiver_id = ? and is_read = 0 and type = 1", user.UserId).Model(&moble.Message{}).Select("count(*)").Find(&Comment)
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "未读获取成功",
		"data": struct {
			Follow  int `json:"follow"`
			Comment int `json:"comment"`
		}{
			Follow:  Follow,
			Comment: Comment,
		},
	})
}

func Readall(context *gin.Context) {
	var user moble.Users
	context.Request.ParseForm()
	us := context.Request.Form.Get("user")
	json.Unmarshal([]byte(us), &user)
	global.DB.Where("receiver_id = ?", user.UserId).Updates(&moble.Message{
		IsRead: 1,
	})
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "全部已读",
	})
}
